package com.voja.mrvica2.rss;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import com.voja.mrvica2.Entry;

public class XMLHandler extends DefaultHandler {
    
    private ArrayList<Entry> data = new ArrayList<Entry>();
    private Entry entry;
    
    private boolean inId        = false;
    private boolean inItem      = false;
    private boolean inItemTitle = false;
    private boolean inItemImage = false;
    private boolean inItemLink  = false;
    private boolean inItemDescription  = false;
    
    @Override
    public void startElement( String     nameSpace,
                              String     name,
                              String     nameQ,
                              Attributes attrs ) {
        
        if (name.equals("item")) {
            inItem = true;
            entry  = new Entry();
        }
        
        if (inItem) {
            if (name.equals("id")) {
                inId = true;
            } else if (name.equals("title")) {
                inItemTitle = true;
            } else if (name.equals("image")) {
                inItemImage = true;
            } else if (name.equals("link")) {
                inItemLink = true;
            } else if (name.equals("description")) {
                inItemDescription = true;
            }
        }
    }
    
    @Override
    public void characters(char ch[], int start, int length) {
        if (inId) {
            entry.setId( Integer.parseInt(new String(ch, start, length)) );
        } else if (inItemTitle) {
            entry.setTitle( new String(ch, start, length) );
        } else if (inItemImage) {
            entry.setImage( new String(ch, start, length) );
        } else if (inItemLink) {
            entry.setLink( new String(ch, start, length) );
        } else if (inItemDescription) {
            entry.setDescription( new String(ch, start, length) );
        }
    }
    
    @Override
    public void endElement( String  nameSpace,
                            String  name,
                            String  nameQ ) {
        
        if (inItem) {
            if (name.equals("id")) {
                inId = false;
            } else if (name.equals("title")) {
                inItemTitle = false;
            } else if (name.equals("image")) {
                inItemImage = false;
            } else if (name.equals("link")) {
                inItemLink = false;
            } else if (name.equals("description")) {
                inItemDescription = false;
            }
        }
        
        if (name.equals("item")) {
            inItem = false;
            data.add(entry);
            entry = null;
        }
    }
    
    public ArrayList<Entry> getEntries() {
        return data;
    }
    public void setEntries(ArrayList<Entry> entries) {
        data = entries;
    }
}
